package com.fjwt.gz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.interfaces.IOfficialService;
import com.fjwt.gz.db.entity.OfficialMaterialEntity;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 公众号素材 服务实现类
 * </p>
 *
 * @author
 * @since 2025-04-09
 */

@Service
@Slf4j
public class OfficialMediaService {

    @Autowired
    private OfficialMenuService officialMenuService;
    @Autowired
    private IOfficialService officialService;
    @Autowired
    private OfficialMaterialService officialMaterialService;

    public JSONObject uploadMedia(String appid, String type, String state, MultipartFile file) {
        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(type) || StringUtils.isEmpty(state)) {
            throw new BizException("请求参数缺失！");
        }
        JSONObject json = new JSONObject();
        WxMpService wxMpService = officialMenuService.setWxService(appid);
        if (ObjectUtil.equal(state, "1")) {
            String result = this.officialService.uploadPicToGzh(appid, null, file, type, wxMpService);
            json.put("data", result);
            log.info("上传临时性素材返回信息：{}", result);
        } else {
            if (ObjectUtil.equal(type, "news")) {
                String result = this.officialService.uploadImgToGzh(appid, null, file, wxMpService);
                log.info("上传永久性图文素材返回信息：{}", JSONObject.toJSONString(result));
            } else {
                String result = this.officialService.uploadFileToGzh(appid, null, file, type, wxMpService);
                log.info("上传永久性素材返回信息：{}", JSONObject.toJSONString(result));
                json.put("data", result);
            }
        }
        return json;
    }

    /**
     * 获取素材列表
     *
     * @param appid
     * @param type
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public WxMpMaterialFileBatchGetResult getMaterialList(String appid, String type, Integer pageNumber, Integer pageSize) {
        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(type) || ObjectUtils.isEmpty(pageNumber) || ObjectUtils.isEmpty(pageSize)) {
            throw new BizException("请求参数缺失！");
        }
        WxMpService wxMpService = officialMenuService.setWxService(appid);
        Integer begin = (pageNumber - 1) * pageSize;
        WxMpMaterialFileBatchGetResult materialList = null;
        try {
            materialList = officialService.getMaterialList(appid, type, begin, pageSize, wxMpService);
        } catch (WxErrorException e) {
            throw new BizException("获取素材列表失败！");
        }
        return materialList;
    }

    /**
     * 获取图文素材列表
     *
     * @param appid
     * @param offset
     * @param count
     * @return
     */
    public WxMpMaterialNewsBatchGetResult getNewsMaterialList(String appid, Integer offset, Integer count) {
        if (StringUtils.isEmpty(appid)) {
            throw new BizException("请求参数缺失！");
        }
        WxMpMaterialNewsBatchGetResult newsMaterialList = null;
        WxMpService wxMpService = officialMenuService.setWxService(appid);
        try {
            newsMaterialList = officialService.getNewsMaterialList(appid, offset, count, wxMpService);
        } catch (WxErrorException e) {
            throw new BizException("获取素材列表失败！");
        }
        return newsMaterialList;
    }

    public boolean deleteMaterial(String appid, String mediaId) {
        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(mediaId)) {
            throw new BizException("请求参数缺失！");
        }
        WxMpService wxMpService = officialMenuService.setWxService(appid);

        boolean flag = false;
        try {
            flag = officialService.deleteMaterial(appid, mediaId, wxMpService);
            LambdaQueryWrapper<OfficialMaterialEntity> officialMaterialQueryWrapper =
                    OfficialMaterialEntity.gw()
                            .eq(OfficialMaterialEntity::getMediaId, mediaId)
                            .eq(OfficialMaterialEntity::getOfficialAppId, appid);
            officialMaterialService.remove(officialMaterialQueryWrapper);
        } catch (WxErrorException e) {
            throw new BizException("公众号素材删除失败！");
        }
        return flag;
    }

    /**
     * 导入公众号素材图片
     *
     * @return
     */
    public void importMaterialImg(String mediaId, String url, String officialAppId, String activityTemplateNo) {
        LambdaQueryWrapper<OfficialMaterialEntity> officialMaterialQueryWrapper = OfficialMaterialEntity.gw()
                .eq(OfficialMaterialEntity::getActivityTemplateNo, activityTemplateNo)
                .eq(OfficialMaterialEntity::getOfficialAppId, officialAppId)
                .eq(OfficialMaterialEntity::getImgUrl, url);
        OfficialMaterialEntity officialMaterial = officialMaterialService.getOne(officialMaterialQueryWrapper);
        if (ObjectUtils.isNotEmpty(officialMaterial)) {
            throw new BizException("该素材已存在！");
        }
        OfficialMaterialEntity officialMaterialEntity = new OfficialMaterialEntity();
        officialMaterialEntity.setOfficialAppId(officialAppId);
        officialMaterialEntity.setActivityTemplateNo(activityTemplateNo);
        officialMaterialEntity.setMediaId(mediaId);
        officialMaterialEntity.setImgUrl(url);
        officialMaterialEntity.setCreatedAt(new Date());
        officialMaterialService.save(officialMaterialEntity);
    }

    /**
     * 公众号素材图片列表
     *
     * @return
     */
    public IPage<OfficialMaterialEntity> getMaterialImgList(IPage page, String activityTemplateNo, String officialAppId) {
        if (ObjectUtils.isEmpty(activityTemplateNo) || ObjectUtils.isEmpty(officialAppId)) {
            throw new BizException("请求参数缺失！");
        }
        LambdaQueryWrapper<OfficialMaterialEntity> gw = OfficialMaterialEntity.gw()
                .eq(OfficialMaterialEntity::getOfficialAppId, officialAppId)
                .eq(OfficialMaterialEntity::getActivityTemplateNo, activityTemplateNo)
                .select(OfficialMaterialEntity::getMediaId, OfficialMaterialEntity::getImgUrl);
        return officialMaterialService.page(page, gw);
    }

    /**
     * 获取活动素材接口
     *
     * @param iPage
     * @param activityTemplateNo
     * @param officialAppId
     * @return
     */
    public IPage<OfficialMaterialEntity> getActivityMaterialList(IPage iPage, String activityTemplateNo, String officialAppId) {
        LambdaQueryWrapper<OfficialMaterialEntity> gw =
                OfficialMaterialEntity.gw()
                        .eq(ObjectUtils.isNotEmpty(officialAppId), OfficialMaterialEntity::getOfficialAppId, officialAppId)
                        .eq(ObjectUtils.isNotEmpty(activityTemplateNo), OfficialMaterialEntity::getActivityTemplateNo, activityTemplateNo)
                        .isNotNull(OfficialMaterialEntity::getActivityTemplateNo);
        return officialMaterialService.page(iPage, gw);
    }
}
